package world.zwq.gulimall.ware.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import world.zwq.common.constant.WareConstant;
import world.zwq.common.utils.PageUtils;
import world.zwq.common.utils.Query;

import world.zwq.gulimall.ware.dao.PurchaseDao;
import world.zwq.gulimall.ware.entity.PurchaseDetailEntity;
import world.zwq.gulimall.ware.entity.PurchaseEntity;
import world.zwq.gulimall.ware.service.PurchaseDetailService;
import world.zwq.gulimall.ware.service.PurchaseService;
import world.zwq.gulimall.ware.service.WareSkuService;
import world.zwq.gulimall.ware.vo.MergeVo;
import world.zwq.gulimall.ware.vo.PurchaseDoneVo;
import world.zwq.gulimall.ware.vo.PurchaseItemDoneVo;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId == null){
            //新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            mergeVo.setPurchaseId(purchaseEntity.getId());
        }
        //检查采购需求状态是正确的
        List<Long> longList = mergeVo.getItems().stream()
                .map(id -> {
                    PurchaseDetailEntity byId = purchaseDetailService.getById(id);
                    return byId;
                })
                .filter(entity -> entity.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()
                        || entity.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())
                .map(PurchaseDetailEntity::getId)
                .collect(Collectors.toList());
        mergeVo.setItems(longList);
        List<Long> items = mergeVo.getItems();
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            entity.setPurchaseId(mergeVo.getPurchaseId());
            entity.setId(i);
            entity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return entity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);
        //更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(mergeVo.getPurchaseId());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        //1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> entities = ids.stream()
                .map(id -> this.getById(id))
                .filter(item -> item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .map(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                    return item;
                })
                .collect(Collectors.toList());

        //2、改变采购单状态
        this.updateBatchById(entities);

        //3、改变采购项目的状态
        entities.forEach(item -> {
            List<PurchaseDetailEntity> list= purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> entityList = list.stream().map(item1 -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                entity.setId(item1.getId());
                return entity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(entityList);
        });
    }

    @Override
    @Transactional
    public void done(PurchaseDoneVo doneVo) {
        //1、改变采购单状态
        Long id = doneVo.getId();
        //2、改变采购想的状态
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        boolean flag = true;
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HAS_ERROR.getCode()){
                flag = false;
            } else {
                //3、将成功的采购进行入库
                PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(purchaseDetailEntity.getSkuId(),purchaseDetailEntity.getWareId(),purchaseDetailEntity.getSkuNum());
            }
            entity.setStatus(item.getStatus());
            entity.setId(item.getItemId());
            updates.add(entity);
        }
        purchaseDetailService.updateBatchById(updates);

        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(id);
        if(flag){
            entity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        } else {
            entity.setStatus(WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode());
        }
        entity.setUpdateTime(new Date());
        this.updateById(entity);

    }

}